"""
This file contains functions that are no longer in active use but are kept for reference.
These functions may be useful in the future or serve as examples for similar functionality.

Note: These functions are not maintained and may not work with current game versions.
"""

# 移动相关函数
def move_to_npc(npc: 'Mobile', target_distance: int):
    """Move closer to an NPC until within specified distance
    
    Args:
        npc: The NPC to move towards
        target_distance: The target distance to reach
        
    Returns:
        bool: True if successfully moved within target distance, False otherwise
    """
    if not npc:
        return False
        
    # Check if already within target distance
    current_distance = Player.DistanceTo(npc)
    if current_distance <= target_distance:
        return True
        
    # Get current positions
    target_x = npc.Position.X
    target_y = npc.Position.Y
    player_x = Player.Position.X
    player_y = Player.Position.Y
    
    # Keep moving until within target distance
    while Player.DistanceTo(npc) > target_distance:
        # Determine direction based on relative positions
        if target_x > player_x and target_y > player_y:
            if not Player.Walk("Southeast"):
                return False
        elif target_x < player_x and target_y > player_y:
            if not Player.Walk("Southwest"):
                return False
        elif target_x > player_x and target_y < player_y:
            if not Player.Walk("Northeast"):
                return False
        elif target_x < player_x and target_y < player_y:
            if not Player.Walk("Northwest"):
                return False
        elif target_x > player_x and target_y == player_y:
            if not Player.Walk("East"):
                return False
        elif target_x < player_x and target_y == player_y:
            if not Player.Walk("West"):
                return False
        elif target_x == player_x and target_y > player_y:
            if not Player.Walk("South"):
                return False
        elif target_x == player_x and target_y < player_y:
            if not Player.Walk("North"):
                return False
            
        # Wait a bit for movement
        Misc.Pause(200)  # 走路速度是每秒5格，所以每步需要200ms
        
        # Update positions
        player_x = Player.Position.X
        player_y = Player.Position.Y
        
    return True

def move_to_item(item: 'Item', target_distance: int):
    """Move closer to an item until within specified distance
    
    Args:
        item: The item to move towards
        target_distance: The target distance to reach
        
    Returns:
        bool: True if successfully moved within target distance, False otherwise
    """
    if not item:
        return False
        
    # Check if already within target distance
    current_distance = Player.DistanceTo(item)
    if current_distance <= target_distance:
        return True
        
    # Get current positions
    target_x = item.Position.X
    target_y = item.Position.Y
    player_x = Player.Position.X
    player_y = Player.Position.Y
    
    # Keep moving until within target distance
    while Player.DistanceTo(item) > target_distance:
        # Determine direction based on relative positions
        if target_x > player_x and target_y > player_y:
            if not Player.Walk("Southeast"):
                return False
        elif target_x < player_x and target_y > player_y:
            if not Player.Walk("Southwest"):
                return False
        elif target_x > player_x and target_y < player_y:
            if not Player.Walk("Northeast"):
                return False
        elif target_x < player_x and target_y < player_y:
            if not Player.Walk("Northwest"):
                return False
        elif target_x > player_x and target_y == player_y:
            if not Player.Walk("East"):
                return False
        elif target_x < player_x and target_y == player_y:
            if not Player.Walk("West"):
                return False
        elif target_x == player_x and target_y > player_y:
            if not Player.Walk("South"):
                return False
        elif target_x == player_x and target_y < player_y:
            if not Player.Walk("North"):
                return False
            
        # Wait a bit for movement
        Misc.Pause(200)  # 走路速度是每秒5格，所以每步需要200ms
        
        # Update positions
        player_x = Player.Position.X
        player_y = Player.Position.Y
        
    return True

def move_to_position_nearby(target_pos, search_radius=1):
    """Find a reachable position near the target and move to it.
    
    Args:
        target_pos: The target position to reach
        search_radius: How many tiles to search around the target (default: 2)
        
    Returns:
        bool: True if successfully moved to a nearby position, False otherwise
    """
    reachable_pos = find_reachable_position_nearby(target_pos, search_radius)
    if not reachable_pos:
        return False
        
    return move_to_position(reachable_pos)

def find_reachable_position_nearby(target_pos, search_radius=2):
    """Find a reachable position near the target, excluding the target position itself.
    
    This function searches for a position that is both:
    1. Near the target position (within search_radius tiles)
    2. Actually reachable by the player (path exists)
    
    Args:
        target_pos: The target position to reach
        search_radius: How many tiles to search around the target (default: 2)
        
    Returns:
        tuple or None: A tuple of (x, y, z) coordinates if found, None otherwise
    """
    # Start from radius 1 to skip the target position itself
    for radius in range(1, search_radius + 1):
        # Check positions in a square pattern around target
        for x in range(-radius, radius + 1):
            for y in range(-radius, radius + 1):
                # Skip positions that are not on the square perimeter
                if abs(x) != radius and abs(y) != radius:
                    continue
                    
                # Create new position by adding offsets
                check_x = target_pos.X + x
                check_y = target_pos.Y + y
                check_z = target_pos.Z
                
                # Check if path exists to this position
                if PathFinding.GetPath(check_x, check_y, check_z):
                    return (check_x, check_y, check_z)
                    
    return None

def move_to_position(target_pos, max_wait_time=10):
    """Move to the specified position.
    
    Args:
        target_pos: The position to move to (tuple of x, y, z or Position object)
        max_wait_time: Maximum time to wait for movement to complete (in seconds)
        
    Returns:
        bool: True if successfully moved to the position, False otherwise
    """
    # Handle both tuple and Position object
    if isinstance(target_pos, tuple):
        x, y, z = target_pos
    else:
        x, y, z = target_pos.X, target_pos.Y, target_pos.Z
        
    # Create route object
    route = PathFinding.Route()
    route.X = x
    route.Y = y
    
    # Move to position
    if not PathFinding.Go(route):
        print(f"Failed to start movement to position ({x}, {y}, {z})")
        return False
        
    # Wait for movement to complete and check position
    start_time = time.time()
    while time.time() - start_time < max_wait_time:
        # Check if we've reached the target position
        current_pos = Player.Position
        if current_pos.X == x and current_pos.Y == y:
            return True
            
        Misc.Pause(100)  # Wait 100ms before next check
        
    print(f"Movement timed out after {max_wait_time} seconds")
    return False


def is_reachable(self, x, y, z=None, ignore_mobs=False):
    """Check if a position is reachable using pathfinding
    
    Args:
        x: X coordinate
        y: Y coordinate
        z: Z coordinate
        ignore_mobs: Whether to ignore mobiles in path calculation
        
    Returns:
        bool: True if position is reachable, False otherwise
    """
    # Get path to destination
    path = PathFinding.GetPath(x, y, ignore_mobs)
    
    if not path:
        print(f"Position ({x}, {y}, {z}) is not reachable")
        return False
        
    # Create route object
    route = PathFinding.Route()
    route.X = x
    route.Y = y
    
    # Check if destination is reachable
    is_reachable = PathFinding.Go(route)
    
    if is_reachable:
        print(f"Position ({x}, {y}, {z}) is reachable")
    else:
        print(f"Position ({x}, {y}, {z}) is not reachable")
        
    return is_reachable



def find_items_in_room(self, room):
    """Find all items within a specified room
    
    Args:
        room: Room object containing the room's boundaries and properties
        
    Returns:
        list: List of items found within the room
    """
    # Create a new filter instance
    filter = Items.Filter()
    
    # Set up filter for visible items
    filter.Enabled = True
    filter.OnGround = True
    
    # Apply filter to find all visible items
    all_items = Items.ApplyFilter(filter)
    
    # Filter items that are inside the room
    room_items = []
    for item in all_items:
        if room.is_inside(item.Position):
            room_items.append(item)
            print(f"Found item in room: {item.Name}")
            print(f"Position: X={item.Position.X}, Y={item.Position.Y}, Z={item.Position.Z}")
            print(f"Serial: 0x{item.Serial:08X}")
            print("---")
    
    print(f"\nFound {len(room_items)} items in room '{room.name}'")
    return room_items 

def find_items_in_room_by_name(self, room, item_name):
    """Find items with specific name within a specified room
    
    Args:
        room: Room object containing the room's boundaries and properties
        item_name: Name of the item to find (case-insensitive)
        
    Returns:
        list: List of items found within the room matching the name
    """
    # First get all items in the room
    room_items = self.find_items_in_room(room)
    
    # Filter items by name
    matching_items = []
    for item in room_items:
        if item_name.lower() in item.Name.lower():
            matching_items.append(item)
            print(f"Found matching item: {item.Name}")
            print(f"Position: X={item.Position.X}, Y={item.Position.Y}, Z={item.Position.Z}")
            print(f"Serial: 0x{item.Serial:08X}")
            print("---")
    
    print(f"\nFound {len(matching_items)} items matching '{item_name}' in room '{room.name}'")
    return matching_items 
def find_visible_items(self):
    """Find all visible items and print their coordinates and names
    
    Returns:
        list: List of found items with their coordinates and names
    """
    # Create a new filter instance
    filter = Items.Filter()
    
    # Set up filter for visible items
    filter.Enabled = True
    filter.OnGround = True
    
    # Apply filter to find items
    items = Items.ApplyFilter(filter)
    
    # Print information about found items
    print(f"\nFound {len(items)} visible items:")
    for item in items:
        print(f"Item: {item.Name}")
        print(f"Position: X={item.Position.X}, Y={item.Position.Y}, Z={item.Position.Z}")
        print(f"Serial: 0x{item.Serial:08X}")
        print("---")
        
    return items 
